package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.itheima.reggie.common.R;
import com.itheima.reggie.contants.MessageConstant;
import com.itheima.reggie.dto.DishDTO;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.DishFlavor;
import com.itheima.reggie.mapper.DishMapper;
import com.itheima.reggie.service.DishFlavorService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.utils.RedisUtils;
import com.itheima.reggie.vo.dishPageVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * 菜品业务层实现
 */
@Service
@Transactional
@Slf4j
public class DishServiceImpl extends ServiceImpl<DishMapper, Dish> implements DishService {

    @Autowired
    private DishMapper dishMapper;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 添加菜品
     *
     * @param dto
     * @return
     */
    @Override
    public R add(DishDTO dto) {
        // 保存菜品基本数据
        this.save(dto);

        // 保存菜品数据成功后，删除对应分类的菜品，下次查询，缓存中没有就会查询数据库
        String key = RedisUtils.createKey("dish", dto.getCategoryId() + "_1");
        redisTemplate.delete(key);
        // 保存菜品口味数据
        List<DishFlavor> flavors = dto.getFlavors();

        // 为口味列表增加菜品ID
        List<DishFlavor> flavorList = flavors.stream().map(item -> {
            // 为每个菜品品味设置菜品ID
            item.setDishId(dto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavorList);

        return R.success(MessageConstant.DISH_SAVE_OK);
    }

    /**
     * 条件分页查询
     *
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @Override
    public R dishPage(Integer page, Integer pageSize, String name) {
        PageHelper.startPage(page, pageSize);
        List<DishDTO> dishList = dishMapper.findAll(name);

        PageInfo<DishDTO> pageInfo = new PageInfo<>(dishList);

        dishPageVo dishPageVo = new dishPageVo();

        dishPageVo.setRecords(pageInfo.getList());
        dishPageVo.setSize(pageInfo.getSize());
        dishPageVo.setTotal(pageInfo.getTotal());

        return R.success(dishPageVo);
    }

    /**
     * 菜品数据回显
     *
     * @param id
     * @return
     */
    @Override
    public R findByWithFlavors(Long id) {
        Dish dish = this.getById(id);
        List<DishFlavor> list = dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, id));
        DishDTO dishDTO = new DishDTO();
        BeanUtils.copyProperties(dish, dishDTO);
        dishDTO.setFlavors(list);

        return R.success(dishDTO);
    }

    /**
     * 修改菜品和口味
     *
     * @param dto
     * @return
     */
    @Override
    public R updateDishWithFlavors(DishDTO dto) {
        // 在更新前，查询菜品原来属于哪个分类 湘菜
        Long id = dto.getId();
        Dish dbDish = this.getById(id);

        // 1.保存菜品基本数据
        this.updateById(dto);

        // 更新  菜品数据成功后，删除对应分类的菜品，下次查询，缓存中没有就会查询数据库
        // a.修改在最新的分类数据
        String key = RedisUtils.createKey("dish", dto.getCategoryId() + "_1");
        redisTemplate.delete(key);

        // 由 湘菜 --> 川菜，就得修改缓存中两个分类的数据
        // b.判断是否修改了菜品的分类
        // dbDish.getCategoryId()   dish原来分类ID
        // dto.getCategoryId()      更新后的分类ID
        if (!dbDish.getCategoryId().equals(dto.getCategoryId())){
            // 修改了菜品的分类、
            key = RedisUtils.createKey("dish", dto.getCategoryId() + "_1");
            redisTemplate.delete(key);
        }

        // 删除原有得菜品口味数据
        dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, dto.getId()));

        // 保存菜品口味数据
        List<DishFlavor> flavors = dto.getFlavors();

        // 为口味列表增长菜品ID
        List<DishFlavor> flavorList = flavors.stream().map(item -> {
            item.setDishId(dto.getId());
            return item;
        }).collect(Collectors.toList());

        dishFlavorService.saveBatch(flavorList);

        return R.success("菜品修改成功");
    }

    /**
     * 批量删除菜品和口味
     *
     * @param ids
     * @return
     */
    @Override
    public R removeDishWithFlavors(Long[] ids) {
        dishMapper.deleteBatchIds(Arrays.asList(ids));

        for (Long id : ids) {
            dishFlavorService.remove(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, id));
        }

        return R.success("删除菜品成功");
    }

    /**
     * 批量修改状态
     *
     * @param dishes
     * @return
     */
    @Override
    public R updateDishStatus(List<Dish> dishes) {

        this.updateBatchById(dishes);
        return R.success("批量更新成功");
    }

    /**
     * 根据分类ID查询菜品
     *
     * @param dto
     * @return
     */
    @Override
    public R findListAndFlavors(DishDTO dto) {
        // 1.从缓冲中获取数据
        // 缓冲菜品的key应该如何设置？dish_分类ID_起售状态
        // 以什么类型的数据来存储菜品数据
        String key = RedisUtils.createKey("dish", dto.getCategoryId() + "_1");
        // 使用RedisTemplate在存储字符串数据时，可能直接存储集合数据，RedisTemplate会对当前数据做序列化操作
        List<DishDTO> dishDtos = (List<DishDTO>) redisTemplate.opsForValue().get(key);

        // 1.1有，直接返回数据
        if (!CollectionUtils.isEmpty(dishDtos)){
            log.info("从缓存中获取数据：{}",dto.getCategoryId());
            return R.success(dishDtos);
        }

        // 1.2没有，则查询数据库，查询后放入缓存

        // 1.2.1 查询数据库
        log.info("从数据库中查询菜品，并存入缓存：{}",dto.getCategoryId());
        LambdaQueryWrapper<Dish> lqw = Wrappers.<Dish>lambdaQuery().eq(dto.getCategoryId() != null, Dish::getCategoryId, dto.getCategoryId())
                .eq(Dish::getStatus, 1)
                .orderByAsc(Dish::getSort)
                .orderByDesc(Dish::getUpdateTime);

        List<Dish> dishes = this.list(lqw);

        dishDtos = dishes.stream().map(item -> {
            DishDTO dishDTO = new DishDTO();
            BeanUtils.copyProperties(item, dishDTO);
            List<DishFlavor> dishFlavors = dishFlavorService.list(Wrappers.<DishFlavor>lambdaQuery().eq(DishFlavor::getDishId, item.getId()));
            dishDTO.setFlavors(dishFlavors);
            return dishDTO;
        }).collect(Collectors.toList());
        // 1.2.2 放入缓存,设置过去时间为1个小时
        redisTemplate.opsForValue().set(key,dishDtos,1, TimeUnit.HOURS);
        return R.success(dishDtos);
    }


}